package com.eipc;

import org.androidpn.sdk.Constants;
import org.androidpn.sdk.ServiceManager;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnKeyListener;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;

import com.eipc.event.OnBarClickListener;
import com.eipc.info.R;
import com.eipc.model.Person;
import com.eipc.util.DBHelper;
import com.eipc.util.HttpManager;
import com.eipc.util.PreferencesHelper;
import com.eipc.util.Tools;
import com.eipc.view.Bar;


public abstract class CommonTabActivity extends TabActivity {
	protected static String currentActivity = null;
	public final static int PROMPT_ID = 0x000100;
	public final static long MAX_INTERVAL = 15*1000;  //二次弹出消息的最大间隔时间，超过这个时间才会弹出
	protected static String CONTROL_CENTER = "CONTROL_CENTER";
	protected static String MAIN = "MAIN";
	public final static String ACTION_POPUP_MESSAGE = "action.intent.popup.message";
	public final static int HANDLER_MESSAGE_POPUP = 1;
	public final static int HANDLER_MESSAGE_CLEAR =2;
	public final static int HANDLER_MESSAGE_UPDATE_VIEW = 3;
	public static boolean isDialogShow = false;
	private Cursor mPopupCursor;
	protected Person mPerson;
	private PopupMessageBroadcast mReiceiver;
	private AudioManager mAudioManager;
	private NotificationManager mNotificationManager;
	private PreferencesHelper mHelper;
//	protected int mLocale;         //当前的语言
	public long owerAct;
	protected String mReplyContent;
	protected String mReplyTime;
	protected String mInfoId;
	protected AlertDialog.Builder mBuilder;
	private long mInterval;    //二次弹出的间隔时间
	private Dialog mPopupDialog;
	private PushFinishBroadcast  mPushReceiver;
	private String mUrl;
	private ServiceManager serviceManager;
	public static long CURRACT;
	public long owerAct1;
	public static Intent mServiceIntent;
	
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		owerAct1 = System.currentTimeMillis();
		CURRACT = owerAct1;
       
        try{
        
		mRe = getResources();
		mDB = DBHelper.getInstance(this);
		mHelper = new PreferencesHelper(getSharedPreferences(Constants.SDK_PREFERENCES, Context.MODE_PRIVATE));
		mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		mBuilder = new Builder(this).setTitle(R.string.tip);
	
		try{
        	TelephonyManager mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
        	String imsi = mTelephonyMgr.getDeviceId().toLowerCase();  
        	mHelper.put(Constants.XMPP_USERNAME,imsi);      
        }catch(Exception e){
        	Log.e("-----XMPP_USERNAME-----","error");
        }
        
		Resources res = getResources();
		Configuration cfg = res.getConfiguration();
//		startPush();
		
		serviceManager = new ServiceManager(this);         
        serviceManager.startService();
        		
		res.updateConfiguration(cfg, null);
		
		if(mServiceIntent==null){
			mServiceIntent = new Intent(this,EipcMainService.class);
			startService(mServiceIntent);
		}
		
		
        }catch(Exception ex){
    		Log.e("----common activity onCreate--------","Error");
    	}
	}
	
	public boolean isMyself(){
		return CURRACT==owerAct1?true:false;
	}
	
	protected void setCurrentActivity(String v) {
		currentActivity = v;
	}
	
	private void startReceiveMessage() {
		mReiceiver = new PopupMessageBroadcast();
		IntentFilter filter = new IntentFilter(ACTION_POPUP_MESSAGE);
		registerReceiver(mReiceiver, filter);
	}
	
	protected Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case HANDLER_MESSAGE_POPUP:
						mPopupCursor = mDB.queryAll(DBHelper.TB_IMPORT_NOTICE,new String[] { DBHelper.FIELD_IMPORT_NOTICE_ID},new String[] { ((Integer)msg.obj).toString()});
						showDailog(mPopupCursor);
						mHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_CLEAR, 1*1000);
					break;
				case HANDLER_MESSAGE_CLEAR:
					mNotificationManager.cancel(PROMPT_ID);
					break;
				case HANDLER_MESSAGE_UPDATE_VIEW:
					doUpdateView();
					break;
			}
		};
	};
	
	class PopupMessageBroadcast extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent!=null){
				long current = System.currentTimeMillis();
				if((mInterval==0 || current - mInterval>MAX_INTERVAL)&&(mPopupDialog==null ||(!mPopupDialog.isShowing()))){
					Integer id = intent.getIntExtra("id",0);
					if(id!=null && id!=0){
						mHandler.sendMessage(mHandler.obtainMessage(HANDLER_MESSAGE_POPUP, id));
						mInterval = current; 
					}
				}else{
					mInterval = current; 
				}
			}
		}
	}
	
	/*
	 * 显示图片
	 */
	private void showPicture(boolean isOk,Bitmap bm){
		if(isOk){
			final Dialog dialog = new Dialog(this);
			dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
			View view = getLayoutInflater().inflate(R.layout.picture_dialog, null);
			ImageView iv = (ImageView)view.findViewById(R.id.iv_picture);
			iv.setImageBitmap(bm);
			dialog.setContentView(view);
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		}
	}

	private void showDailog(final Cursor info) {
		if (info != null && info.getCount() > 0 &&!isDialogShow) {
			info.moveToFirst();
			mPopupDialog = new Dialog(this);
			mPopupDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
			mPopupDialog.setCancelable(false);
			View view = getLayoutInflater().inflate(
					R.layout.control_center_dialog, null);
			TextView tv = (TextView) view.findViewById(R.id.content);
			tv.setText(info.getString(info
					.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_CONTENT)));
			final int type = info.getInt(info.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_APPTYPE));
			TextView titleView = (TextView)view.findViewById(R.id.dialog_title);
			switch(type){
				case DBHelper.APP_TYPE_IMPORT_NOTICE://重要通知
					titleView.setText(getString(R.string.dialog_import_notice_title,getString(R.string.import_notice)));
					break;
				case DBHelper.APP_TYPE_ME_REPORT://我要找茬
					titleView.setText(getString(R.string.dialog_import_notice_title,getString(R.string.me_report)));
					break;
//				case DBHelper.APP_TYPE_WORK_REPORT://工作汇报
//					titleView.setText(getString(R.string.dialog_import_notice_title,getString(R.string.work_report)));
//					break;
			}
			tv = (TextView) view.findViewById(R.id.issuer);
			tv.setText(Html.fromHtml(mRe.getString(
					R.string.control_signer,mDB.getPersonName(
					info.getString(info
							.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_ISSUER))),
					info.getString(info
							.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_ISSUE_TIME)))));
			tv = (TextView) view.findViewById(R.id.sender);
			tv.setText(Html.fromHtml(mRe.getString(
					R.string.control_publishor,mDB.getPersonName(
					info.getString(info
							.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_SENDER))),
					info.getString(info
							.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_SEND_TIME)))));
			Button b = (Button) view.findViewById(R.id.sure_close);
			mInfoId = info.getString(info
					.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_ID));
			Log.e("---------------mNoticeId----------------",mInfoId);
			final EditText et = (EditText)view.findViewById(R.id.statuses);
			final Button down = (Button)view.findViewById(R.id.ib_down);
//			if(type==DBHelper.APP_TYPE_WORK_REPORT) et.setText(R.string.status_work_report);
			down.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					final ListView listView = (ListView)getLayoutInflater().inflate(R.layout.list, null);
					final Dialog dialog = new Dialog(CommonTabActivity.this);
					ArrayAdapter<CharSequence> adapter = null;
//					if(type!=DBHelper.APP_TYPE_WORK_REPORT){
//						adapter = ArrayAdapter.createFromResource(
//			                CommonTabActivity.this, R.array.status, R.layout.spinner);
//					}
//					else{
						adapter = ArrayAdapter.createFromResource(
								CommonTabActivity.this, R.array.status2, R.layout.spinner);
//					}
					listView.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							et.setText((CharSequence)listView.getItemAtPosition(position));
							dialog.dismiss();
						}
					});
			        listView.setAdapter(adapter);
			        dialog.setContentView(listView);
			        dialog.show();
				}
			});
			b.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
//					mReplyContent = (String)et.getText().toString();
//					mReplyTime = Tools.getCurrentTimeString();
					mPopupDialog.dismiss();
					isDialogShow = false;
//					mDB.updateImportNotice(Integer.parseInt(mInfoId),mReplyContent,mReplyTime);
//					mDB.insertUploadReply(mInfoId,mReplyContent,mReplyTime);
//					Intent i = new Intent("action.push.finish");
//			    	sendBroadcast(i);
				}
			});
			String webImage = info.getString(info.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_IMAGE_WEBURL));
			b = (Button)view.findViewById(R.id.btn_look);
			if(webImage!=null && !"".equals(webImage)){
				b.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mUrl = info.getString(info.getColumnIndexOrThrow(DBHelper.FIELD_IMPORT_NOTICE_IMAGE_WEBURL));
						new LoadImageTask().execute();
					}
				});
			}
			else{
				b.setVisibility(View.GONE);
			}
			mPopupDialog.setContentView(view);
			mPopupDialog.setOnKeyListener(new OnKeyListener() {
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
					Log.e("---------onKeyDown-----------","-----------keyCode-"+keyCode+"---isDialogShow : " + String.valueOf(isDialogShow));
					if(keyCode == KeyEvent.KEYCODE_BACK){
						Log.e("---------KeyEvent.KEYCODE_BACK-----------","-----------KeyEvent.KEYCODE_BACK----isDialogShow : " + String.valueOf(isDialogShow));
						if(isDialogShow){
							View view = getLayoutInflater().inflate(R.layout.control_center_dialog, null);
							final EditText et = (EditText)view.findViewById(R.id.statuses);
							mReplyContent = (String)et.getText().toString();
							mReplyTime = Tools.getCurrentTimeString();
							mPopupDialog.dismiss();
							isDialogShow = false;
							mDB.updateImportNotice(Integer.parseInt(mInfoId),mReplyContent,mReplyTime);
							mDB.insertUploadReply(mInfoId,mReplyContent,mReplyTime);
							Intent i = new Intent("action.push.finish");
					    	sendBroadcast(i);
						}
					}
					return false;
				}
			});
			isDialogShow = true;
			mPopupDialog.show();
		}
	}
	
	
	protected View buildLabel(int label){
    	LayoutInflater inflater = getLayoutInflater();
    	Button btn = (Button)inflater.inflate(R.layout.label, null);
    	btn.setText(label);
    	return btn;
    }

	protected void doUpdateView(){
		if(isMyself()){
			Log.e("-----------isMyself begin updateView----------","update");
			updateView();
		}else{
			Log.e("-----------is not Myself dont updateView----------","do not update");
		}
	}
	
	
	
    protected void updateView(){
	}
	
	protected void startPush(){
		mPushReceiver = new PushFinishBroadcast();
		IntentFilter filter = new IntentFilter("action.push.finish");
		registerReceiver(mPushReceiver, filter);
	}
	
	protected void stopPush(){
		try {
			if(mPushReceiver!=null) unregisterReceiver(mPushReceiver);
		} catch (Exception e) {
		}
	}
	
	/*
	 * push结束广播
	 */
	class PushFinishBroadcast extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			mHandler.sendEmptyMessage(CommonActivity.HANDLER_MESSAGE_UPDATE_VIEW);
		}
	}
	


	
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// if(keyCode == KeyEvent.KEYCODE_CALL && mBar!=null){
		// mBar.getBtnLeft().dispatchKeyEvent(new
		// KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_CALL));
		// return true;
		// }
		// if(keyCode == KeyEvent.KEYCODE_ENDCALL && mBar!=null){
		// mBar.getBtnRight().dispatchKeyEvent(new
		// KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_ENDCALL));
		// return true;
		// }
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onPause() {
		super.onPause();
		stopPush();
		if(mInfos.isFlipping()) mInfos.stopFlipping(); 
//		mBottomBar.startFlipper();
		if(mReiceiver!=null) unregisterReceiver(mReiceiver);
	}

	@Override
	protected void onResume() {
		super.onResume();
//		new FetchOtherTask(this,mDB, new OnFetchOtherFinishedListener() {	
//			@Override
//			public void OnFinished(ArrayList<News> news) {
//				if(news!=null && news.size()>0){
//					for(News n : news){
//						mInfos.addView(getNewsView(n));
//						mInfos.startFlipping();
//					}
//				}
//				else{
//					mInfos.addView( mInflater.inflate(R.layout.news_item, null));
//				}
//				mBottomBar.startFlipper();
//			}
//		}).execute(mLocale);
//		startReceiveMessage();
//		startPush();
//		mBottomBar.setMode(mHelper.getBoolean(CommonActivity.PERFERENCE_MODE));
//		int language = mHelper.getInt(CommonActivity.PERFERENCE_LANGUAGE);
//		if(mLocale!=language){
//			mLocale = language;
//			Intent i = new Intent(this, this.getClass());
//			startActivity(i);
//			finish();
//		}
		
		mPopupCursor = mDB.nearlyNotice();
		if(mPopupCursor!=null&&mPopupCursor.getCount()>0){
			showDailog(mPopupCursor);
			mHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_CLEAR, 1*1000);
		}
		
//		new FetchOtherTask(CommonTabActivity.this, mDB, new OnFetchOtherFinishedListener() {	
//			@Override
//			public void OnFinished(ArrayList<News> news) {
//				if(news!=null && news.size()>0){
//					for(News n : news){
//						mInfos.addView(getNewsView(n));
//						mInfos.startFlipping();
//					}
//				}
//				else{
//					mInfos.addView( mInflater.inflate(R.layout.news_item, null));
//				}
//				mBottomBar.startFlipper();
//			}
//		}).execute(mLocale);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mPopupCursor!=null) mPopupCursor.close();
		if(mDB!=null) mDB.close();
		mNotificationManager.cancel(PROMPT_ID);
	}

	protected void initView() {
		mBuilder = new Builder(this).setTitle(R.string.tip);
		mBar = (Bar) findViewById(R.id.bar);
//		mBottomBar = (BottomBar) findViewById(R.id.bottomBar);
		mInfos = (ViewFlipper) findViewById(R.id.infos);
		mInflater = getLayoutInflater();
		mPerson = mDB.getMeBySim();

		mBar.setOnBarClickListener(new OnBarClickListener() {

			@Override
			public void onClickRight() {
				
			}

			@Override
			public void onClickLeft() {
//				Intent i = new Intent(CommonTabActivity.this,MainActivity.class);
//				startActivity(i);
//				finish();
			}
		});
		
//		 new FetchOtherTask(this,mDB, new OnFetchOtherFinishedListener() {	
//				@Override
//				public void OnFinished(ArrayList<News> news) {
//					if(news!=null && news.size()>0){
//						for(News n : news){
//							mInfos.addView(getNewsView(n));
//						}
//					}
//					else{
//						mInfos.addView( mInflater.inflate(R.layout.news_item, null));
//					}
//					mInfos.startFlipping();
//				}
//			}).execute();
	}
	
	

	
	public void closeDialog(){
		mPopupDialog.dismiss();
		isDialogShow = false;
	}
	
	protected Bar mBar;
	protected DBHelper mDB;
//	protected BottomBar mBottomBar;
	protected Resources mRe;
	protected ProgressDialog mDialog;
	protected ViewFlipper mInfos;
	protected LayoutInflater mInflater;
	

	
	
//	class PollingTask extends CommonTask<Void>{
//		public PollingTask(){
//			super(CommonTabActivity.this);
//		}
//		private String noticeResult;
////		private String weatherResult;
////		private SerInfoResponse matchSir;
////		private SerInfoResponse scoreSir;
//		private boolean isOk;
//		
//		@Override
//		protected Void doInBackground(Void... params) {
//			Log.i("--"+this.getClass().getName(),"------------------runing------------------");
//			try {
//				SharedPreferences sdkPreferences = getSharedPreferences(Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
//				String mobileID = sdkPreferences.getString(Constants.XMPP_USERNAME,"");
//				String maxID    = sdkPreferences.getString(Constants.MaxId,"0");
//				String ids = mDB.getIDs();
//				noticeResult  = HttpManager.polling(getString(R.string.url_polling),Constants.TTYPE_NOTICE,maxID,ids,mobileID,"0");
////				weatherResult = HttpManager.polling(getString(R.string.url_polling),Constants.TTYPE_WEATHER,maxID,ids,mobileID,"0");
////				matchSir = HttpManager.loadSerInfo(getString(R.string.url_load_serinfo),mobileID,Constants.MACH,Constants.LOAD_MODEL_MATCH);
////				scoreSir = HttpManager.loadSerInfo(getString(R.string.url_load_serinfo),mobileID,Constants.SCORE,Constants.LOAD_MODEL_SCORE);
////	            try{mDB.insertMatch((Match[])matchSir.os);}catch(Exception e){
////	            	Log.e("-----insertMatch------","-------error-------");
////	            }
////				try{mDB.insertScore((Score[])scoreSir.os);}catch(Exception e){
////					Log.e("-----insertScore------","-------error-------");
////				}
//				
//			} catch (Exception e) {
////				MyLog.error(FetchConsultService.class,"",e);
//			}
//			if(XmppManager.isLogin){
//				isOk = true;
//			}
//			return null;
//		}
//	}
	
	class LoadImageTask extends CommonTask<Void>{
		private Bitmap mBitmap;

		public LoadImageTask(){
			super(CommonTabActivity.this,getString(R.string.loadImage));
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			Log.e("-------------------url : ",mUrl);
			if(mUrl!=null&&!"".equals(mUrl)){
				String u = mRe.getString(R.string.url_img,mUrl);
				Log.e("-------------------u : ",u);
				mBitmap = HttpManager.getURLBitmap(u);
			}else{
				showPicture(false,null);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Log.e("-------------------bm : ",String.valueOf(mBitmap));
			if(mBitmap != null){
				showPicture(true,mBitmap);
			}else{
				showPicture(false,null);
			}
		}
	}
}
